﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using CE.Provider;
using CE.Global;

public partial class Provider_CarInsurance_ProviderCarYear : System.Web.UI.Page
{
    string PageName = "CXCI";
    string SubPageName = "CXCIVHYR";
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        //{
        //    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
        //        Convert.ToInt32(CE.Global.CEUserType.Provider))
        //    {
        //        Response.Redirect("~/Provider/ProviderSecureLogin.aspx");
        //    }
        //}
        //else
        //{
        //    Response.Redirect("~/Provider/ProviderSecureLogin.aspx");
        //}

        if (Session[CE.Global.General.UserId] == null || Session[CE.Global.General.ProviderCompanyId] == null)
        {
            Response.Redirect("~/Provider/ProviderSecureLogin.aspx");
        }
        CheckMainPageAccess();
        CheckSubPageAccess();

        if (!Page.IsPostBack)
        {
            usrEffectivityDate.StartYear = CE.Global.General.GetUTCDateTime().Year;
            usrEffectivityDate.EndYear = CE.Global.General.GetUTCDateTime().Year + 2; 

            lblProviderCarYearId.Text = "0";
            lblProviderCarYearId.Visible = false;
            //Sakthi on 28 Dec 2010 -- Start
            //int _startYear = 1900;
            //int _endyear = CE.Global.General.GetUTCDateTime().Year;

            //for (int i = _startYear; i <= _endyear; i++)
            //{
            //    ddlFromYear.Items.Add(i.ToString());
            //    ddlToYear.Items.Add(i.ToString());
            //}
            int _startYear = 0;
            int _endyear = 15;

            for (int i = _startYear; i <= _endyear; i++)
            {
                ddlFromYear.Items.Add(i.ToString());
                ddlToYear.Items.Add(i.ToString());
            }
            //Sakthi on 28 Dec 2010 -- End
            ddlToYear.Items.Insert(0, new ListItem("Select", "-1"));
            ddlFromYear.Items.Insert(0, new ListItem("Select", "-1"));
            ddlToYear.Text = "-1";
            ddlFromYear.Text = "-1";

            CarCoverTypeList _carcoverlist = new CarCoverTypeList();
            CarCoverTypeDB _carcovertypedb = new CarCoverTypeDB();
            _carcoverlist = _carcovertypedb.GetProviderCoverTypeList(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()));

            if (_carcoverlist != null)
            {
                for (int i = 0; i < _carcoverlist.Count; i++)
                {
                    ddlCoverType.Items.Add(new ListItem(_carcoverlist[i].ProviderCoverTypeDescription.ToString(), _carcoverlist[i].CXCoverTypeId.ToString()));
                }
            }

            ddlCoverType.Items.Insert(0, new ListItem("Select", "-1"));
            ddlCoverType.Text = "-1";

            ClearFields();

            if (Page.Request.Params["FromYear"] != null &&
                    Page.Request.Params["ToYear"] != null &&
                Page.Request.Params["CXCoverTypeId"] != null)
            {
                int _fYear = 0;
                int _tYear = 0;
                int _cxcovertypeid = 0;

                if (int.TryParse(Page.Request.Params["FromYear"].ToString(), out _fYear) &&
                   int.TryParse(Page.Request.Params["ToYear"].ToString(), out _tYear) &&
                    int.TryParse(Page.Request.Params["CXCoverTypeId"].ToString(), out _cxcovertypeid))
                {
                    ddlFromYear.Text = _fYear.ToString();
                    ddlToYear.Text = _tYear.ToString();
                    ddlCoverType.Text = _cxcovertypeid.ToString();
                    ShowCarYear(_fYear, _tYear, _cxcovertypeid);
                }

            }
        }
    }

    protected void ibtSubmit_Click(object sender, ImageClickEventArgs e)
    {
        if (Page.IsValid)
        {
            string _authcode = CE.Security.MySecurity.Encrypt(txtAuthCode.Text, true);
            if (CheckAuthCode(_authcode, 100))
            {
                CarYear _caryear = new CarYear();
                CarYearDB _caryeardb = new CarYearDB();

                if (lblProviderCarYearId.Text != "0")
                {
                    _caryear.ProviderCarYearId = Convert.ToInt64(lblProviderCarYearId.Text);
                    if (CheckCarYearDuplicate(_caryear.ProviderCarYearId, Convert.ToInt32(ddlFromYear.Text), Convert.ToInt32(ddlToYear.Text), Convert.ToInt32(ddlCoverType.Text)))
                    {
                        lblMessage.Text = "This year setting already exist.";
                        return;
                    }
                }
                else
                {
                    _caryear.ProviderCarYearId = CheckCarYear(Convert.ToInt32(ddlFromYear.Text), Convert.ToInt32(ddlToYear.Text), Convert.ToInt32(ddlCoverType.Text));
                }

                int _trantype = 1;
                
                if (_caryear.ProviderCarYearId > 0)
                {
                    _trantype = 2;
                }

                _caryear.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                _caryear.ProviderCompanyId = Convert.ToInt64(Session[General.ProviderCompanyId].ToString());

                _caryear.FromYear = Convert.ToInt32(ddlFromYear.Text);
                _caryear.ToYear = Convert.ToInt32(ddlToYear.Text);
                _caryear.CXCoverTypeId = Convert.ToInt32(ddlCoverType.Text);
                _caryear.YearRate = Convert.ToSingle(txtCoverageRate.Text);
                _caryear.Status = chkStatus.Checked;

                string otherinfo = "";
                if (rdoEffectivity.SelectedValue == "Yes" && usrEffectivityDate.GetDate() > CE.Global.General.GetUTCDateTime())
                {
                    _caryear.FInfo1 = float.Parse(txtNewRate.Text);
                    _caryear.DInfo1 = usrEffectivityDate.GetDate();

                    otherinfo = "Cover Type: " + ddlCoverType.SelectedItem.Text + "<br/>"
                        + "From Year: " + ddlFromYear.Text + "<br/>"
                        + "To Year: " + ddlToYear.Text + "<br/>"
                        + "Current Rate: " + txtCoverageRate.Text + "<br/>"
                        + "New Rate: " + txtNewRate.Text + "<br/>"
                        + "Effectivity Date: " + usrEffectivityDate.GetDate() + "<br/>";
                }
                else
                {
                    _caryear.FInfo1 = float.Parse(txtCoverageRate.Text);
                    _caryear.DInfo1 = CE.Global.General.GetUTCDateTime();

                    otherinfo = "Cover Type: " + ddlCoverType.SelectedItem.Text + "<br/>"
                        + "From Year: " + ddlFromYear.Text + "<br/>"
                        + "To Year: " + ddlToYear.Text + "<br/>"
                        + "Current Rate: " + txtCoverageRate.Text + "<br/>";

                }
                _caryear.ProviderCarYearId = _caryeardb.Insert(_caryear);
                if (_caryear.ProviderCarYearId > 0)
                {
                    InsertProviderAuthTransaction(_caryear.ProviderCarYearId, "CICarYear", _trantype, 100, _authcode, _caryear.ProviderCompanyId, _caryear.RefCEUserId);
                    ProviderUpdateSave(_caryear.ProviderCarYearId);
                    lblMessage.Text = "Updated successfully!";
                    Response.Redirect("ViewProviderCarYear.aspx");
                }
                else
                {
                    lblMessage.Text = "Updating failed.";
                }
            }
            else
            {
                lblMessage.Text = "Wrong auth code!";
            }
        }
    }

    private void ProviderUpdateSave(Int64 ProviderRefId)
    {
        ProviderUpdates _providerupdates = new ProviderUpdates();
        ProviderUpdatesDB _providerupdatesDB = new ProviderUpdatesDB();

        _providerupdates.UpdateId = 0;
        _providerupdates.CXTableId = GetCXTableId();
        _providerupdates.ProviderRefId = ProviderRefId;

        if (rdoEffectivity.SelectedValue == "Yes" && usrEffectivityDate.GetDate() > CE.Global.General.GetUTCDateTime())
        {
            //Scheduled
            _providerupdates.UpdateType = 1;
        }
        else
        {
            //Immediate
            _providerupdates.UpdateType = 0;
        }

        _providerupdates.ProviderCompanyId = Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId]);
        _providerupdates.RefCEUserID = Convert.ToInt64(Session[General.UserId].ToString());

        _providerupdatesDB.Insert(_providerupdates);

    }

    private Int32 GetCXTableId()
    {
        Int32 CXID = 0;

        ProviderTableListings _tablelist = new ProviderTableListings();
        ProviderTableListingsDB _tablelistdb = new ProviderTableListingsDB();

        int ProviderType = 100; //Car Insurance
        string CXTable = "tblProviderCarYear";

        _tablelist = _tablelistdb.GetProviderTableListingsSingleItem(ProviderType, Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId]), CXTable);

        if (_tablelist != null)
            CXID = _tablelist.CXTableId;

        return CXID;

    }

    protected void CheckStartYear(object sender, ServerValidateEventArgs args)
    {
        if (ddlFromYear.Text != "-1" && ddlToYear.Text != "-1")
        {
            int _fYear = Convert.ToInt32(ddlFromYear.Text);
            int _toYear = Convert.ToInt32(ddlToYear.Text);
            if (_fYear > _toYear)
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }
    }

    protected void ShowCarYear(int FromYear, int ToYear, int CXCoverTypeId)
    {
        CarYear _caryear = new CarYear();
        CarYearDB _caryeardb = new CarYearDB();

        _caryear = _caryeardb.GetProviderCarYear(FromYear, ToYear, Convert.ToInt64(Session[General.ProviderCompanyId].ToString()), CXCoverTypeId);

        if (_caryear != null)
        {
            lblProviderCarYearId.Text = _caryear.ProviderCarYearId.ToString();
            txtCoverageRate.Text = _caryear.YearRate.ToString("#.00");
            chkStatus.Checked = _caryear.Status;

            if (_caryear.DInfo1 > CE.Global.General.GetUTCDateTime())
            {
                divNewRate.Visible = true;
                txtNewRate.Text = _caryear.FInfo1.ToString();
                rdoEffectivity.SelectedValue = "Yes";
            }
            else
            {
                divNewRate.Visible = false;
                rdoEffectivity.SelectedValue = "No";
            }

            usrEffectivityDate.Day = _caryear.DInfo1.Day;
            usrEffectivityDate.Month = _caryear.DInfo1.Month;
            usrEffectivityDate.Year = _caryear.DInfo1.Year;
        }
    }

    protected Int64 CheckCarYear(int FromYear, int ToYear, int CXCoverTypeId)
    {
        CarYear _caryear = new CarYear();
        CarYearDB _caryeardb = new CarYearDB();
        Int64 _retValue = 0;
        _caryear = _caryeardb.GetProviderCarYear(FromYear, ToYear, Convert.ToInt64(Session[General.ProviderCompanyId].ToString()), CXCoverTypeId);

        if (_caryear != null)
        {
            _retValue = _caryear.ProviderCarYearId;
        }

        return _retValue;
    }
    
    protected bool CheckCarYearDuplicate(Int64 CurrentProviderCarYearId, int FromYear, int ToYear, int CXCoverTypeId)
    {
        CarYear _caryear = new CarYear();
        CarYearDB _caryeardb = new CarYearDB();
        bool _retValue = false;
        _retValue = _caryeardb.CheckProviderCarYearDuplicate(CurrentProviderCarYearId, FromYear, ToYear, Convert.ToInt64(Session[General.ProviderCompanyId].ToString()), CXCoverTypeId);
        return _retValue;
    }

    private bool CheckSelectionStatus()
    {
        bool _retValue = false;
        if (ddlCoverType.Text != "-1" && ddlFromYear.Text != "-1" && ddlToYear.Text != "-1")
        {
            _retValue = true;
        }
        return _retValue;
    }

    protected void ddlFromYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (CheckSelectionStatus())
        //{
        //    ShowCarYear(Convert.ToInt32(ddlFromYear.Text), Convert.ToInt32(ddlToYear.Text), Convert.ToInt32(ddlCoverType.Text));
        //}

        //csvYear.Validate();
    }

    protected void ddlToYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (CheckSelectionStatus())
        //{
        //    ShowCarYear(Convert.ToInt32(ddlFromYear.Text), Convert.ToInt32(ddlToYear.Text), Convert.ToInt32(ddlCoverType.Text));
        //}
        //csvYear.Validate();
    }

    protected void ddlCoverType_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (CheckSelectionStatus())
        //{
        //    ShowCarYear(Convert.ToInt32(ddlFromYear.Text), Convert.ToInt32(ddlToYear.Text), Convert.ToInt32(ddlCoverType.Text));
        //}
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        rfvAuthCode.Validate();
        if (lblProviderCarYearId.Text != "0" && txtAuthCode.Text.Trim().Length > 0)
        {
            //Int64 _caryearid = CheckCarYear(Convert.ToInt32(ddlFromYear.Text), Convert.ToInt32(ddlToYear.Text), Convert.ToInt32(ddlCoverType.Text));
            Int64 _caryearid = Convert.ToInt64(lblProviderCarYearId.Text);
            Int64 _providercompanyid = Convert.ToInt64(Session[General.ProviderCompanyId].ToString());
            string _authcode = CE.Security.MySecurity.Encrypt(txtAuthCode.Text, true);
            Int64 _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
            if (CheckAuthCode(_authcode, 100))
            {
                if (_caryearid != 0)
                {
                    CarYearDB _caryeardb = new CarYearDB();
                    if (_caryeardb.Delete(_caryearid, _providercompanyid))
                    {
                        InsertProviderAuthTransaction(_caryearid, "CICarYear", 3, 100, _authcode, _providercompanyid, _refceuserid);
                        Response.Redirect("ViewProviderCarYear.aspx");
                    }
                    else
                    {
                        lblMessage.Text = "Deleting failed.";
                    }
                }
            }
            else
            {
                lblMessage.Text = "Wrong auth code!";
            }
        }
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        ClearFields();
    }

    public void EffectiveWhen(object sender, EventArgs e)
    {
        if (rdoEffectivity.SelectedValue == "Yes")
        {
            divNewRate.Visible = true;
        }
        else
        {
            divNewRate.Visible = false;
        }

        usrEffectivityDate.Day = CE.Global.General.GetUTCDateTime().Day;
        usrEffectivityDate.Month = CE.Global.General.GetUTCDateTime().Month;
        usrEffectivityDate.Year = CE.Global.General.GetUTCDateTime().Year;
    }

    protected void ClearFields()
    {
        lblProviderCarYearId.Text = "0";
        ddlCoverType.Text = "-1";
        ddlFromYear.Text = "-1";
        ddlToYear.Text = "-1";
        txtCoverageRate.Text = "";
        chkStatus.Checked = false;
        lblMessage.Text = "";
    }

    protected void ibtBack_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("ViewProviderCarYear.aspx");
    }

    protected bool CheckAuthCode(string strAuthCode, int intAuthCodeType)
    {
        bool _retValue = false;
        ProviderAuthCode _authcode = new ProviderAuthCode();
        ProviderAuthCodeDB _authcodedb = new ProviderAuthCodeDB();
        _authcode = _authcodedb.GetProviderAuthCode(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()), intAuthCodeType, strAuthCode);
        if (_authcode != null)
        {
            _retValue = true;
        }

        return _retValue;
    }

    protected Int64 InsertProviderAuthTransaction(Int64 TransactionId, string TransactionCode, int TransactionType,
        int AuthCodeType, string AuthCode, Int64 ProviderCompanyId, Int64 RefCEUserId)
    {

        ProviderAuthTransaction _authtrans = new ProviderAuthTransaction();
        ProviderAuthTransactionDB _authtransdb = new ProviderAuthTransactionDB();

        _authtrans.TransactionId = TransactionId;
        _authtrans.TransactionCode = TransactionCode;
        _authtrans.TransactionType = TransactionType;
        _authtrans.AuthCode = AuthCode;
        _authtrans.AuthCodeType = AuthCodeType;
        _authtrans.ProviderCompanyId = ProviderCompanyId;
        _authtrans.RefCEUserID = RefCEUserId;

        _authtrans.AuthTransId = _authtransdb.Insert(_authtrans);
        return _authtrans.AuthTransId;
    }

    private void CheckMainPageAccess()
    {
        Int64 PageAccess = General.GetProviderMainPageAccess(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()),
                                                        Convert.ToInt64(Session[General.UserId].ToString()), PageName);
        if (PageAccess == 0)
        {
            //Response.Redirect("~/Provider/UserMessage.aspx?errorcode=2000");
            Response.Redirect("~/Provider/UserMessage.aspx?mt=UM&ec=2000");
        }
    }

    private void CheckSubPageAccess()
    {
        Int64 PageAccess = General.GetProviderSubPageAccess(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()),
                                                        Convert.ToInt64(Session[General.UserId].ToString()), SubPageName);
        if (PageAccess == 0)
        {
            //Response.Redirect("~/Provider/UserMessage.aspx?errorcode=2000");
            Response.Redirect("~/Provider/UserMessage.aspx?mt=UM&ec=2000");
        }
        else if (PageAccess == 100)
        {
            ibtSubmit.Enabled = false;
            btnNew.Enabled = false;
            btnDelete.Enabled = false;
        }
        else if (PageAccess == 200)
        {
            ibtSubmit.Enabled = true;
            btnNew.Enabled = true;
            btnDelete.Enabled = false;
        }
        else if (PageAccess == 300)
        {
            ibtSubmit.Enabled = true;
            btnNew.Enabled = true;
            btnDelete.Enabled = true;
        }
    }

}
